layui.use(['layer', 'form', 'table', 'element'], function() {
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var element = layui.element;
    var $ = layui.$;

    // 初始化表格
    function initTables() {
        // 全部待办表格
        table.render({
            elem: '#allTodos',
            url: '/api/todos',
            parseData: function(res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.length,
                    "data": res
                };
            },
            cols: [[
                {field: 'title', title: '标题'},
                {field: 'description', title: '描述'},
                {field: 'completed', title: '状态', templet: function(d) {
                    return d.completed ? '已完成' : '未完成';
                }},
                {field: 'created_at', title: '创建时间', templet: function(d) {
                    return new Date(d.created_at).toLocaleString();
                }},
                {title: '操作', toolbar: '#allTodosBar'}
            ]],
            page: true
        });

        // 未完成待办表格
        table.render({
            elem: '#activeTodos',
            url: '/api/todos?completed=false',
            parseData: function(res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.length,
                    "data": res
                };
            },
            cols: [[
                {field: 'title', title: '标题'},
                {field: 'description', title: '描述'},
                {field: 'created_at', title: '创建时间', templet: function(d) {
                    return new Date(d.created_at).toLocaleString();
                }},
                {title: '操作', toolbar: '#activeTodosBar'}
            ]],
            page: true
        });

        // 已完成待办表格
        table.render({
            elem: '#completedTodos',
            url: '/api/todos?completed=true',
            parseData: function(res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.length,
                    "data": res
                };
            },
            cols: [[
                {field: 'title', title: '标题'},
                {field: 'description', title: '描述'},
                {field: 'completed_at', title: '完成时间', templet: function(d) {
                    return new Date(d.completed_at).toLocaleString();
                }},
                {title: '操作', toolbar: '#completedTodosBar'}
            ]],
            page: true
        });
    }

    // 监听工具条事件
    table.on('tool(allTodos)', function(obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            showEditModal(data);
        } else if (obj.event === 'delete') {
            deleteTodo(data.id);
        } else if (obj.event === 'complete') {
            completeTodo(data.id);
        }
    });

    table.on('tool(activeTodos)', function(obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            showEditModal(data);
        } else if (obj.event === 'delete') {
            deleteTodo(data.id);
        } else if (obj.event === 'complete') {
            completeTodo(data.id);
        }
    });

    table.on('tool(completedTodos)', function(obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            showEditModal(data);
        } else if (obj.event === 'delete') {
            deleteTodo(data.id);
        } else if (obj.event === 'uncomplete') {
            uncompleteTodo(data.id);
        }
    });

    // 显示添加待办模态框
    window.showAddTodoModal = function() {
        layer.open({
            type: 1,
            title: '添加待办事项',
            content: $('#todoModal'),
            area: ['500px', '400px'],
            success: function() {
                form.val('todoForm', {
                    title: '',
                    description: ''
                });
            }
        });
    };

    // 显示编辑待办模态框
    function showEditModal(data) {
        layer.open({
            type: 1,
            title: '编辑待办事项',
            content: $('#todoModal'),
            area: ['500px', '400px'],
            success: function() {
                form.val('todoForm', {
                    title: data.title,
                    description: data.description
                });
            }
        });
    }

    // 监听表单提交
    form.on('submit(todoForm)', function(data) {
        var formData = data.field;
        var url = '/api/todos';
        var method = 'POST';

        if (data.elem.id === 'editForm') {
            url += '/' + data.elem.dataset.id;
            method = 'PUT';
        }

        axios({
            method: method,
            url: url,
            data: formData
        }).then(function(response) {
            layer.closeAll();
            layer.msg('操作成功', {icon: 1});
            table.reload('allTodos');
            table.reload('activeTodos');
            table.reload('completedTodos');
        }).catch(function(error) {
            layer.msg('操作失败: ' + error.message, {icon: 2});
        });

        return false;
    });

    // 删除待办事项
    function deleteTodo(id) {
        layer.confirm('确定要删除这个待办事项吗？', {icon: 3, title: '提示'}, function(index) {
            axios.delete('/api/todos/' + id)
                .then(function(response) {
                    layer.close(index);
                    layer.msg('删除成功', {icon: 1});
                    table.reload('allTodos');
                    table.reload('activeTodos');
                    table.reload('completedTodos');
                })
                .catch(function(error) {
                    layer.msg('删除失败: ' + error.message, {icon: 2});
                });
        });
    }

    // 完成待办事项
    function completeTodo(id) {
        axios.put('/api/todos/' + id + '/complete')
            .then(function(response) {
                layer.msg('已完成', {icon: 1});
                table.reload('allTodos');
                table.reload('activeTodos');
                table.reload('completedTodos');
            })
            .catch(function(error) {
                layer.msg('操作失败: ' + error.message, {icon: 2});
            });
    }

    // 取消完成待办事项
    function uncompleteTodo(id) {
        axios.put('/api/todos/' + id + '/uncomplete')
            .then(function(response) {
                layer.msg('已取消完成', {icon: 1});
                table.reload('allTodos');
                table.reload('activeTodos');
                table.reload('completedTodos');
            })
            .catch(function(error) {
                layer.msg('操作失败: ' + error.message, {icon: 2});
            });
    }

    // 初始化
    initTables();
}); 